
const TAGS_VIEW_TYPES = {
  TAG: 'TAG',
  TAGS: 'TAGS',
  RESET_TAGS: 'RESET_TAGS',
  UPDATE_GETTER_FLAG: 'UPDATE_GETTER_FLAG'
};

const state = {
  tag: {},
  resetTags: [],
  tags: {},
  updateGetterFlag: null
};

const getters = {
  getUserTags: (state, getters) => (userId) => {
    console.log('Should update getter?', state.updateGetterFlag);
    if (state.updateGetterFlag) {
      // 强制触发计算属性的重新计算
      const updatedTags = getters.getUserTags(userId);
      return updatedTags;
    } else {
      return state.tags[userId] || [];
    }
  },
  // 新的计算属性，用于判断是否重新计算getUserTags
  // shouldUpdateGetter: (state) => {
  //   return state.updateGetterFlag;
  // }
};

const mutations = {
  [TAGS_VIEW_TYPES.TAG] (state, { userId, tag = {} }) {
    tag.meta = { isAffix: false };
    if (tag.url === "/") {
      tag.url = tag.index;
    }
    if (!state.tags[userId]) {
      state.tags[userId] = []; // 初始化tags数组
    }
    const foundIndex = state.tags[userId].findIndex(
      ({ menuId }) => menuId === tag.menuId);
    if (foundIndex === -1) {
      state.tags[userId].push(tag);
    }
  },
  [TAGS_VIEW_TYPES.TAGS] (state, { userId, tag = {} }) {
    const foundIndex = state.tags[userId]?.findIndex(
      ({ menuId }) => menuId === tag.menuId
    );
    if (foundIndex !== -1) {
      state.tags[userId]?.splice(foundIndex, 1);
    }
  },
  [TAGS_VIEW_TYPES.RESET_TAGS] (state, { userId, resetTags = [] }) {
    if (!state.tags[userId]) {
      state.tags[userId] = []; // 初始化tags数组
    }
    state.tags[userId] = resetTags;
  },
  // 新增的mutation，用于标记需要重新计算getter
  [TAGS_VIEW_TYPES.UPDATE_GETTER_FLAG] (state, flag) {
    state.updateGetterFlag = flag;
  }
};

const actions = {
  async setTagsview ({ commit }, { userId, tag }) {
    commit(TAGS_VIEW_TYPES.TAG, { userId, tag });
  },
  async closeTagsView ({ commit }, { userId, tag }) {
    // 更新updateGetterFlag为true，表示需要重新计算getter
    commit(TAGS_VIEW_TYPES.UPDATE_GETTER_FLAG, true);
    commit(TAGS_VIEW_TYPES.TAGS, { userId, tag });
    // 更新完tags后，将updateGetterFlag重新设置为false，停止重新计算getter
    commit(TAGS_VIEW_TYPES.UPDATE_GETTER_FLAG, false);
  },
  async resetTagsView ({ commit }, { userId, resets }) {
    commit(TAGS_VIEW_TYPES.RESET_TAGS, { userId, resetTags: resets });
    commit(TAGS_VIEW_TYPES.UPDATE_GETTER_FLAG, false);
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};